﻿using Ionic.Zip;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TZL.Data;
using TZL.Web.Models;

namespace TZL.Web.Controllers
{
    public class AdminController : AdminLoginBaseController
    {
        #region 后台菜单控制器
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Category()
        {
            return View();
        }

        public ActionResult News()
        {
            using (var context = new PortalEntities())
            {
                var query = from item in context.Categeries
                            select new KeyValue
                            {
                                Key = item.CategoryId,
                                Value = item.CategoryName
                            };

                ViewBag.CategoryList = query.ToList();
            }
            return View();
        }

        public ActionResult DataConfig()
        {
            using (var context = new PortalEntities())
            {
                var query = from item in context.Configs
                            select new KeyValue
                            {
                                Key = item.Id,
                                Value = item.ConfigKey
                            };

                ViewBag.ConfigList = query.ToList();
            }
            return View();
        }

        public ActionResult UserFile()
        {

            return View();
        }

        public JsonResult FileList()
        {
            try
            {
                using (var context = new PortalEntities())
                {
                    var query = from item in context.UserFiles
                                select item;

                    return Json(query.ToList());
                }
            }
            catch (Exception e)
            {
                return Json(null);
            }
        }
        #endregion

        #region 操作类型
        /// <summary>
        /// 返回集合
        /// </summary>
        /// <param name="unit"></param>
        /// <returns></returns>
        public JsonResult SelectCategoryList()
        {
            int pageIndex = 0;
            int.TryParse(Request["page"], out pageIndex);

            int pageSize = 0;
            int.TryParse(Request["rows"], out pageSize);

            try
            {
                using (var context = new PortalEntities())
                {
                    var query = (from item in context.Categeries
                                 orderby item.CreateTime descending
                                 select item
                                 ).ToList();
                    if (pageIndex == 0 || pageSize == 0)
                    {
                        return Json(query, JsonRequestBehavior.AllowGet);
                    }
                    var page = new Pager(pageIndex, pageSize);
                    var data = query.Skip(page.OffSet).Take(page.Limit).ToList();
                    page.Total = query.Count;

                    if (query.Any())
                    {
                        return Json(new { total = page.Total, pages = page.Pages, rows = data }, JsonRequestBehavior.AllowGet);
                    }
                    return Json(new { total = 0, pages = 0, rows = "" }, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception)
            {
                return Json(null);
            }
        }

        /// <summary>
        /// 添加类型
        /// </summary>
        /// <param name="category"></param>
        /// <returns></returns>
        public JsonResult AddCategory(Categery category)
        {
            if (category == null || category.BelongUnit == null)
            {
                return Json(new { result = false });
            }
            using (var context = new PortalEntities())
            {
                if (category != null && category.CategoryId <= 0)
                {
                    category.CreateTime = DateTime.Now;
                    context.Categeries.Add(category);
                }
                else
                {
                    var oldCategory = (from item in context.Categeries
                                       where item.CategoryId == category.CategoryId
                                       select item).FirstOrDefault();
                    if (oldCategory != null)
                    {
                        oldCategory.BelongUnit = category.BelongUnit;
                        oldCategory.CategoryName = category.CategoryName;
                        oldCategory.CreateTime = DateTime.Now;
                    }
                }
                var count = context.SaveChanges();
                if (count > 0)
                {
                    return Json(new { result = true });
                }
            }
            return Json(new { result = false });
        }

        /// <summary>
        /// 删除类型
        /// </summary>
        /// <param name="categoryId"></param>
        /// <returns></returns>
        public JsonResult DeleteCategory(int categoryId)
        {
            using (var context = new PortalEntities())
            {
                Categery category = new Categery() { CategoryId = categoryId };
                context.Categeries.Attach(category);
                context.Categeries.Remove(category);

                var count = context.SaveChanges();
                if (count > 0)
                {
                    return Json(new { result = true });
                }
            }
            return Json(new { result = false });
        }
        #endregion

        #region 简要信息
        /// <summary>
        /// 通过类型ID来查询返回简要数据Json
        /// </summary>
        /// <returns></returns>
        public JsonResult SelectNewsList(int categoryId = 0)
        {
            int pageIndex = 0;
            int.TryParse(Request["page"], out pageIndex);

            int pageSize = 0;
            int.TryParse(Request["rows"], out pageSize);

            using (var context = new PortalEntities())
            {
                var query = (from n in context.News
                             join c in context.Categeries on n.CategoryId equals c.CategoryId
                             where n.CategoryId == categoryId || categoryId == 0
                             orderby n.PublishTime descending
                             select new Models.NewsModel
                             {
                                 NewId = n.NewId,
                                 CategoryId = c.CategoryId,
                                 CategoryName = c.CategoryName,
                                 Title = n.Title,
                                 ImgUrl = n.ImgUrl,
                                 Tag = n.Tag,
                                 Brief = n.Brief,
                                 Content = n.Content,
                                 PublishTime = n.PublishTime
                             }).ToList();

                if (pageIndex == 0 || pageSize == 0)
                {
                    return Json(query, JsonRequestBehavior.AllowGet);
                }
                var page = new Pager(pageIndex, pageSize);
                var data = query.Skip(page.OffSet).Take(page.Limit).ToList();
                page.Total = query.Count;

                if (query.Any())
                {
                    return Json(new { total = page.Total, pages = page.Pages, rows = data }, JsonRequestBehavior.AllowGet);
                }
                return Json(new { total = 0, pages = 0, rows = "" }, JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 通过类型ID来查询返回实体
        /// </summary>
        /// <param name="categoryId"></param>
        /// <returns></returns>
        public JsonResult SelectNewsListById(int categoryId)
        {
            using (var context = new PortalEntities())
            {
                var query = (from n in context.News
                             join c in context.Categeries on n.CategoryId equals c.CategoryId
                             where n.CategoryId == categoryId
                             orderby n.PublishTime descending
                             select new Models.NewsModel
                             {
                                 NewId = n.NewId,
                                 CategoryId = c.CategoryId,
                                 CategoryName = c.CategoryName,
                                 Title = n.Title,
                                 ImgUrl = n.ImgUrl,
                                 Tag = n.Tag,
                                 Brief = n.Brief,
                                 Content = n.Content,
                                 PublishTime = n.PublishTime
                             }).ToList();
                return Json(query);
            }
        }
        /// <summary>
        /// 通过类型ID来返回数据的实体集合
        /// </summary>
        /// <param name="categoryId"></param>
        /// <returns></returns>
        public List<News> SelectBriefInfoListByCatId(int categoryId)
        {
            using (var context = new PortalEntities())
            {
                var query = (from item in context.News
                             where item.CategoryId == categoryId
                             select item).ToList();
                return query;
            }
        }
        /// <summary>
        /// 添加或者修改新闻信息
        /// </summary>
        /// <param name="news"></param>
        /// <returns></returns>
        [ValidateInput(false)]
        public JsonResult AddNews(News news)
        {
            if (news == null)
            {
                return Json(new { result = false });
            }

            if (news.CategoryId == 1)
            {
                news.Tag = Request["Tag1"];
            }

            using (var context = new PortalEntities())
            {
                if (news != null && news.NewId <= 0)//添加操作
                {
                    news.PublishTime = news.PublishTime == DateTime.MinValue ? DateTime.Now : news.PublishTime;
                    context.News.Add(news);
                }
                else//修改操作
                {
                    var oldBriefInfo = (from item in context.News
                                        where item.NewId == news.NewId
                                        select item).FirstOrDefault();
                    if (oldBriefInfo != null)
                    {
                        oldBriefInfo.CategoryId = news.CategoryId;
                        oldBriefInfo.Content = news.Content;
                        oldBriefInfo.ImgUrl = news.ImgUrl;
                        oldBriefInfo.Tag = news.Tag;
                        oldBriefInfo.Title = news.Title;
                        oldBriefInfo.Brief = news.Brief;
                        oldBriefInfo.PublishTime = news.PublishTime == DateTime.MinValue ? DateTime.Now : news.PublishTime;
                    }
                }
                var count = context.SaveChanges();
                if (count > 0)
                {
                    return Json(new { result = true });
                }
            }
            return Json(new { result = false });
        }

        /// <summary>
        /// 通过当前记录ID删除相应的记录
        /// </summary>
        /// <param name="briefId"></param>
        /// <returns></returns>
        public JsonResult DeleteNews(int newsId)
        {
            using (var context = new PortalEntities())
            {
                News briefInfo = new News() { NewId = newsId };
                context.News.Attach(briefInfo);
                context.News.Remove(briefInfo);
                var count = context.SaveChanges();
                if (count > 0)
                {
                    return Json(new { result = true });
                }
            }
            return Json(new { result = false });
        }
        #endregion



        #region 配置信息操作
        public JsonResult DeleteConfig(int configId)
        {
            using (var context = new PortalEntities())
            {
                Config configInfo = new Config() { Id = configId };
                context.Configs.Attach(configInfo);
                context.Configs.Remove(configInfo);

                var count = context.SaveChanges();
                if (count > 0)
                {
                    return Json(new { result = true });
                }
            }
            return Json(new { result = false });
        }

        public JsonResult AddConfig(Config config)
        {
            if (config == null)
            {
                return Json(new { result = false });
            }

            using (var context = new PortalEntities())
            {
                if (config != null && config.Id <= 0)//添加操作
                {
                    config.ModifyTime = DateTime.Now;
                    context.Configs.Add(config);
                }
                else//修改操作
                {
                    var oldConfigInfo = (from item in context.Configs
                                         where item.Id == config.Id
                                         select item).FirstOrDefault();
                    if (oldConfigInfo != null)
                    {
                        oldConfigInfo.Id = config.Id;
                        oldConfigInfo.Content = config.Content;
                        oldConfigInfo.ConfigKey = config.ConfigKey;
                        oldConfigInfo.Description = config.Description;
                        oldConfigInfo.Link = config.Link;
                        oldConfigInfo.ModifyTime = DateTime.Now;
                    }
                }
                var count = context.SaveChanges();
                if (count > 0)
                {
                    return Json(new { result = true });
                }
            }
            return Json(new { result = false });
        }

        public JsonResult SelectConfig(string configKey)
        {
            int pageIndex = 0;
            int.TryParse(Request["page"], out pageIndex);

            int pageSize = 0;
            int.TryParse(Request["rows"], out pageSize);

            try
            {
                using (var context = new PortalEntities())
                {
                    var query = (from item in context.Configs
                                 where item.ConfigKey == configKey
                                 select item).ToList();
                    if (pageIndex == 0 || pageSize == 0)
                    {
                        return Json(query, JsonRequestBehavior.AllowGet);
                    }
                    var page = new Pager(pageIndex, pageSize);
                    var data = query.Skip(page.OffSet).Take(page.Limit).ToList();
                    page.Total = query.Count;

                    if (query.Any())
                    {
                        return Json(new { total = page.Total, pages = page.Pages, rows = data }, JsonRequestBehavior.AllowGet);
                    }
                    return Json(new { total = 0, pages = 0, rows = "" }, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception e)
            {
                return Json(null);
            }
        }
        #endregion

        #region 查询出用户的上传文件
        public JsonResult SelectFiles()
        {
            int pageIndex = 0;
            int.TryParse(Request["page"], out pageIndex);

            int pageSize = 0;
            int.TryParse(Request["rows"], out pageSize);

            using (var context = new PortalEntities())
            {
                var query = (from uf in context.UserFiles
                             join up in context.UploadFiles on uf.Id equals up.UserID
                             orderby uf.UploadTime descending
                             select new Models.UpFiles
                             {
                                 UserId = uf.Id,
                                 FileAdress = up.FileAdress,
                                 FileKinds = up.FileKinds,
                                 UploadTime = uf.UploadTime,
                                 UserName = uf.UserName
                             }).ToList();

                if (pageIndex == 0 || pageSize == 0)
                {
                    return Json(query, JsonRequestBehavior.AllowGet);
                }
                var page = new Pager(pageIndex, pageSize);
                var data = query.Skip(page.OffSet).Take(page.Limit).ToList();
                page.Total = query.Count;

                if (query.Any())
                {
                    return Json(new { total = page.Total, pages = page.Pages, rows = data }, JsonRequestBehavior.AllowGet);
                }
                return Json(new { total = 0, pages = 0, rows = "" }, JsonRequestBehavior.AllowGet);
            }
        }

        public JsonResult SelectFilesByUserId(int userId)
        {
            int pageIndex = 0;
            int.TryParse(Request["page"], out pageIndex);

            int pageSize = 0;
            int.TryParse(Request["rows"], out pageSize);

            using (var context = new PortalEntities())
            {
                var query = (from uf in context.UserFiles
                             join up in context.UploadFiles on uf.Id equals up.UserID
                             where up.UserID == userId
                             orderby uf.UploadTime descending
                             select new Models.UpFiles
                             {
                                 UserId = uf.Id,
                                 FileAdress = up.FileAdress,
                                 FileKinds = up.FileKinds,
                                 UploadTime = uf.UploadTime,
                                 UserName = uf.UserName
                             }).ToList();

                if (pageIndex == 0 || pageSize == 0)
                {
                    return Json(query, JsonRequestBehavior.AllowGet);
                }
                var page = new Pager(pageIndex, pageSize);
                var data = query.Skip(page.OffSet).Take(page.Limit).ToList();
                page.Total = query.Count;

                if (query.Any())
                {
                    return Json(new { total = page.Total, pages = page.Pages, rows = data }, JsonRequestBehavior.AllowGet);
                }
                return Json(new { total = 0, pages = 0, rows = "" }, JsonRequestBehavior.AllowGet);
            }
        }

        public void BatchLoad(int userId)
        {
            using (var context = new PortalEntities())
            {
                var query = (from uf in context.UserFiles
                             join up in context.UploadFiles on uf.Id equals up.UserID
                             where up.UserID == userId
                             orderby uf.UploadTime descending
                             select new Models.UpFiles
                             {
                                 FileAdress = up.FileAdress,
                             }).ToList();
                string name = "UserFiles.zip";
                Response.Clear();
                Response.ContentType = "application/zip";
                Response.AddHeader("content-disposition", "filename=" + name + "");
                using (ZipFile zip = new ZipFile(System.Text.Encoding.Default))//解决中文乱码问题  
                {
                    foreach (var item in query)
                    {
                        string filePath = Server.MapPath(item.FileAdress);
                        zip.AddFile(filePath, "");
                    }
                    zip.Save(Response.OutputStream);
                    Response.Flush();
                    Response.End();
                }
            }
        }
        #endregion
    }

    #region 分页参数类
    public class Pager
    {
        public Pager(int pageIndex, int pageSize)
        {
            if (pageIndex <= 0)
            {
                pageIndex = 1;
            }
            if (pageSize <= 0)
            {
                pageSize = 10;
            }

            PageIndex = pageIndex;
            PageSize = pageSize;

            OffSet = (PageIndex - 1) * PageSize;

            Limit = PageSize;
        }

        public int PageIndex { get; private set; }

        public int PageSize { get; private set; }

        public int OffSet { get; private set; }

        public int Limit { get; set; }

        public int Total { get; set; }

        public int Pages
        {
            get
            {
                if (Total % PageSize > 0)
                {
                    return Total / PageSize + 1;
                }
                return Total / PageSize;
            }
        }
    }
    #endregion
}